package Util;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import Modelo.Endereco;
import Modelo.Estados;

public class CepDadosPiker {

	private String cep;
	private static String URL = "http://cep.republicavirtual.com.br/web_cep.php?formato=xml&cep=";
	private Endereco end;
	
	public CepDadosPiker(String cep) {
		this.cep = cep;
		this.end = new Endereco();
	}
	
	private String getUrlCompleta(){
		String cepFor = "";
		for(int i = 0; i<cep.length(); i++){
			char d = cep.charAt(i);
			if(Character.isDigit(d)){
				cepFor += d;
			}
		}
		return URL + cepFor;
	}
	
	public Endereco getEndereco(){
		SAXBuilder sb = new SAXBuilder(); //Este documento agora possui toda a estrutura do arquivo.  
	    Document d = null;
		try {
			d = sb.build(new StringReader(requisicaoGet()));
			Element mural = d.getRootElement();
			if(mural.getChildText("uf").isEmpty() || mural.getChildText("resultado").equalsIgnoreCase("0")){
				end.setCep("0");
			}else{
				end.setCep(cep);			
				end.setBairro(mural.getChildText("bairro"));
				String tipoLog = mural.getChildText("tipo_logradouro")+ " ";
			    end.setRua(tipoLog + mural.getChildText("logradouro"));
			    end.setCidade(mural.getChildText("cidade"));
			    String uf = mural.getChildText("uf");
			    end.setEstado(Estados.valueOf(uf));
			    return end;
			}
		} catch (JDOMException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	      
	    return end; 
	    
	}
	
	private String requisicaoGet(){
		HttpURLConnection connection = null;
		try{
		   URL url = new URL(getUrlCompleta());      
		  connection = (HttpURLConnection)url.openConnection();
		  InputStream content = connection.getInputStream();
		  Scanner leitor = new Scanner(content);
		  String arquivo = new String("");		 
		  while (leitor.hasNext()) {
			arquivo += leitor.nextLine();				
		  }
		  return arquivo;
		}catch(Exception e){
			e.printStackTrace();
		}
		return "";
	}
	
	
}
